package com.mycode.chapter05.valves;

import org.apache.catalina.*;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Enumeration;

public class HeaderLoggerValve implements Valve, Contained {

    private Container container;
    @Override
    public String getInfo() {
        return null;
    }

    @Override
    public void invoke(Request request, Response response, ValveContext context) throws IOException, ServletException {
        System.out.println("enter HeaderLoggerValve");

        context.invokeNext(request, response);

        System.out.println("Header Logger Valve");
        ServletRequest servletRequest = request.getRequest();
        if (servletRequest instanceof HttpServletRequest) {
            HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
            Enumeration headerNames = httpServletRequest.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                String headerName = headerNames.nextElement().toString();
                String headerValve = httpServletRequest.getHeader(headerName);
                System.out.println(headerName + ":" + headerValve);
            }
        }
        else {
            System.out.println("Not an HTTP Request");
        }
        System.out.println(">>>>>>>>>>>> HeaderLoggerValve <<<<<<<<<<<<<");

    }

    @Override
    public Container getContainer() {
        return container;
    }

    @Override
    public void setContainer(Container container) {
        this.container = container;
    }
}
